import { isEmpty } from "../validator";
import { randomInt } from "./math";

export function remove<T>(arr: Array<T>, ...values: T[]): Array<T> {
    if (Array.isArray(arr) && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
            if (values.includes(arr[i])) { arr.splice(i, 1); i--; }
        }
    } return arr;
}

export function pushUnique<T>(arr: Array<T>, ...values: T[]): number {
    arr.push(...values.filter(value => !arr.includes(value)));
    return arr.length;
}
export function random<T>(arr: Array<T>, except: T = null): T {
    if (isEmpty(arr)) return null;
    if (!!except) arr = remove(arr, except);
    if (isEmpty(arr)) return null;
    else return arr[randomInt(0, arr.length - 1)];
}
export function sortBy<T>(arr: Array<T>, ...props: string[]): T[] {
    arr.sort((v1: T, v2: T) => getProperty(v1) - getProperty(v2));
    function getProperty(v: T): any {
        let _v = v;
        for (let path of [...props]) {
            _v = _v[path];
            if (!_v) return null;
        }
        return _v;
    }
    return arr;
}
export function difference<T>(arr: T[], compared: T[]): T[] {
    return [...arr].filter(value => !compared.includes(value));
}
